import { SearchOutlined, CloseSquareOutlined, PoweroffOutlined } from '@ant-design/icons';
import { Button, Input, Space, Table, Pagination, Image, Select } from 'antd';
import React, { useCallback, useEffect, useRef, useState, useLayoutEffect } from 'react';
import Highlighter from 'react-highlight-words';
import request, { baseUrl } from '../../../utils/request';
import { useNavigate } from 'react-router-dom';
const { Option } = Select;
// const data = [
//     {
//         key: '1',
//         name: 'John Brown',
//         age: 32,
//         address: 'New York No. 1 Lake Park',
//     },
//     {
//         key: '2',
//         name: 'Joe Black',
//         age: 42,
//         address: 'London No. 1 Lake Park',
//     },
//     {
//         key: '3',
//         name: 'Jim Green',
//         age: 32,
//         address: 'Sidney No. 1 Lake Park',
//     },
//     {
//         key: '4',
//         name: 'Jim Red',
//         age: 32,
//         address: 'London No. 2 Lake Park',
//     },
// ];
const Text = () => {
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const [tags, setTags] = useState('全部')
    const [data, setData] = useState([])
    const [page, setPage] = useState(1)
    const [size, setSize] = useState(10)
    const classes = ['全部', '动作', '喜剧', '爱情', '科幻', '悬疑', '剧情', '动画', '冒险', '纪录', '剧集', '演唱会']
    const navigate = useNavigate()

    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const onSelectChange = (newSelectedRowKeys) => {
        // console.log('selectedRowKeys changed: ', newSelectedRowKeys);

        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
        selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,
            {
                key: 'odd',
                text: 'Select Odd Row',
                onSelect: (changableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return false;
                        }
                        return true;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
            {
                key: 'even',
                text: 'Select Even Row',
                onSelect: (changableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return true;
                        }
                        return false;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
        ],
    };
    const getData = async (tags) => {
        // let tag = args.join('')
        let movielistAll
        if (tags == '全部') {
            movielistAll = await request.get('/list/search', {
                params: {
                    page,
                    size,
                }
            })
        } else {
            movielistAll = await request.get('/list/show/category/' + tags, {
                params: {
                    page,
                    size,
                }
            })
        }

        const movielist = movielistAll.data.movielist.data
        movielist.map((item, idx) => {
            item.key = item.movieID
        })
        setData(movielistAll.data.movielist.data)
        // console.log(data);
    }
    const changPage = (page, size) => {
        navigate('?/page=' + page + '&size=' + size)
        console.log(page);
        console.log(size);
        setPage(page)
        setSize(size)
        // console.log(page, size);
    }
    const handleChange = (value) => {
        setTags(value)
        getData(tags)
    }
    useEffect(() => {
        getData(tags)
    }, [tags, page, size])
    useLayoutEffect(() => {
        getData('全部')
    }, [])
    // console.log(data);
    const searchInput = useRef(null);
    const handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    };
    const handleReset = (clearFilters) => {
        clearFilters();
        setSearchText('');
    };
    const getColumnSearchProps = (dataIndex) => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
            <div
                style={{
                    padding: 8,
                }}
            >
                <Input
                    ref={searchInput}
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{
                        marginBottom: 8,
                        display: 'block',
                    }}
                />
                <Space>
                    <Button
                        type="primary"
                        onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
                        icon={<CloseSquareOutlined />}
                        size="small"
                        style={{
                            width: 90,
                        }}
                    >
                        搜索
                    </Button>
                    <Button
                        onClick={() => clearFilters && handleReset(clearFilters)}
                        size="small"
                        style={{
                            width: 90,
                        }}
                    >
                        全部
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        onClick={() => {
                            confirm({
                                closeDropdown: false,
                            });
                            setSearchText(selectedKeys[0]);
                            setSearchedColumn(dataIndex);
                        }}
                    >
                        过滤
                    </Button>
                </Space>
            </div>
        ),
        filterIcon: (filtered) => (
            <SearchOutlined
                style={{
                    color: filtered ? '#1890ff' : undefined,
                }}
            />
        ),
        onFilter: (value, record) =>
            record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownOpenChange: (visible) => {
            if (visible) {
                setTimeout(() => searchInput.current?.select(), 100);
            }
        },
        render: (text) =>
            searchedColumn === dataIndex ? (
                <Highlighter
                    highlightStyle={{
                        backgroundColor: '#ffc069',
                        padding: 0,
                    }}
                    searchWords={[searchText]}
                    autoEscape
                    textToHighlight={text ? text.toString() : ''}
                />
            ) : (
                text
            ),
    });
    const columns = [
        {
            title: '电影名字',
            dataIndex: 'title',
            key: 'title',
            width: '30%',
            ...getColumnSearchProps('title'),
        },
        {
            title: '电影类型',
            dataIndex: 'videoClass',
            key: 'videoClass',
            width: '20%',
            ...getColumnSearchProps('videoClass'),
        },
        {
            title: '地址',
            dataIndex: 'address',
            key: 'address',
            ...getColumnSearchProps('address'),

        },
        {
            title: '电影海报',
            dataIndex: 'imgNames',
            key: 'imgNames',
            render: (text, record, index) => {
                // console.log(record);
                return (
                    <Image height='100px' src={baseUrl + '/imgs/' + record.imgNames}>

                    </Image>
                )
            }


        },
        {
            title: '删除',
            dataIndex: 'delete',
            key: 'delete',
            // render: ()

        },
    ];
    const [loadings, setLoadings] = useState([]);
    const enterLoading = (index) => {
        setLoadings((prevLoadings) => {
            const newLoadings = [...prevLoadings];
            newLoadings[index] = true;
            return newLoadings;
        });
        setTimeout(() => {
            setLoadings((prevLoadings) => {
                const newLoadings = [...prevLoadings];
                newLoadings[index] = false;
                return newLoadings;
            });
        }, 6000);
    };


    return (
        <>
            <Select
                defaultValue="类型"
                style={{
                    width: 120,
                }}
                onChange={handleChange}
            >
                {
                    classes.map((item, idx) => {

                        return <Option key={idx} value={item}>{item}</Option>
                    })
                }

            </Select>
            <Button
                type="primary"
                icon={<PoweroffOutlined />}
                loading={loadings[1]}
                onClick={() => enterLoading(1)}
            >
                Click me!
            </Button>
            <Table rowSelection={rowSelection} columns={columns} dataSource={data} />;
            <Pagination onChange={changPage} defaultCurrent={1} total={6000} />
        </>
    )
};
export default Text;